using System;
using System.Text;
using System.Web.Mvc;

namespace MovieDB.HTMLHelper
{
    public static class MyHtmlHelpers
    {
        public static string Pager(this HtmlHelper helper,string pageBaseUrl, int currentPage, int pageSize, int total)
        {
            double totalPages = total * 1.0 / pageSize;
            // round total pages up to the nearest integer since we cant have something like 10.5 pages 
            totalPages = (int) Math.Ceiling(totalPages);

            if (totalPages == 1)
            {
                return string.Empty;
            }

            var tagBuilder = new TagBuilder("div class='paging'");
            var sb = new StringBuilder();

            for (int currIndex = 0; currIndex < totalPages; currIndex++)
            {
                int actualPage = currIndex + 1;

                if (currIndex == currentPage)
                {
                    sb.AppendFormat("<span class='current'>{0}</span>", actualPage);
                }
                else
                {
                    sb.Append(CreateLink(pageBaseUrl, actualPage));
                }
            }

            tagBuilder.InnerHtml = sb.ToString();

            return tagBuilder.ToString();
        }


        private static string CreateLink(string pageBaseUrl, int currentPage)
        {
            var tagBuilder = new TagBuilder("a class='notActivePagingPage'");
            var queryAppendParameter = pageBaseUrl.Contains("?") ? "&" : "?";
            
            string address = string.Format("{0}{1}page={2}", pageBaseUrl, queryAppendParameter, (currentPage - 1));
            tagBuilder.MergeAttribute("href", address);
            tagBuilder.SetInnerText(currentPage.ToString());

            return tagBuilder.ToString();
        }
    }
}